import React, { PropTypes, Component } from 'react';
import Table from './MyTable'
import Column from './Column'
import { myAjax, getAuthShop, ROOTURL_TABLE } from './../publicAPI/publicAPI';
import styles from './SimpleTable.css';

export default React.createClass({
  getInitialState: function() {
    let date = new Date();
    return {
      year: date.getFullYear(),
      tData: [{}],
      shopsForAdm: [],
      areaArray: [],
      processData: [{}],
      areaSelect: '请选择地区',
    };
  },
  componentWillMount: function() {
    let _this = this;
  },
  componentDidMount: function() {
    let _this = this;
    this.getData();
  },
  getData: function() {
    let _this = this;
    console.log('执行getData');
    myAjax(ROOTURL_TABLE + 'cafune/shop/turnoversummary.api', 'POST', {year:this.state.year}, function(data) {
      this.setState({
        processData: data,
      }, () => {
        getAuthShop(null, function(data) {
          _this.setState({
            shopsForAdm: data,
          }, () => {
            // 处理数据格式为[{}]
            let processData = [];
            let ids = _this.state.processData.shopIds;

            for(var i in ids) {
              let id = ids[i];
              processData.push(_this.state.processData[id]);
            }
            // 获取权限列表数组(有重复数据)
            let shopsForAdm = [];
            _this.state.shopsForAdm.forEach((shopMes) => {
              shopsForAdm.push(shopMes.dname);
            }); 
            // 过滤获取有权限数据与权限列表去重
            let areaArray = new Set();
            let permissionData = processData.filter((data) => {
              if(shopsForAdm.indexOf(data['shopName']) === -1) {
                return false
              } else {
                areaArray.add(data.shopLoc);
                return true 
              }
            });
            // 设置相应state，并回调执行地区筛选
            _this.setState({
              processData: permissionData,
              areaArray: Array.from(areaArray),
            }, () => {
              _this.filterData();
            });
          });
        }.bind(_this));
      });
    }.bind(_this), function(err) {});
  },
  changeArea: function(e) {
    let _this = this;
    let areaSelect = e.target.value;
    this.setState({
      areaSelect: areaSelect,
    }, () => {
      _this.filterData();
    });
  },
  filterData: function() {// 按地区筛选数据
    let _this = this;
    let areaSelect = this.state.areaSelect;
    let selectData = this.state.processData.filter((data) => {
      return areaSelect == '请选择地区'||data.shopLoc == areaSelect
    });
    this.setState({
      tData: selectData,
    });
  },
  handleClick: function() {
    let _this = this;
    let yearSelect = parseInt(this.refs.yearSelect.value);
    if(!yearSelect || !(/^2\d{3}$/.test(yearSelect))) {
      alert("内容不能为空或格式错误");
      this.refs.yearSelect.focus();
      return
    }
    this.setState({
      year: yearSelect,
    }, _this.getData());
  },
  handleKeyPress: function(e) {
    if(e.which == 13) {
      this.handleClick();
    }
  },
  render: function() {
    return (
      <div>
        <div>
          <select value={this.state.areaSelect} onChange={this.changeArea}>
            <option value="请选择地区">请选择地区</option>
            {
              !this.state.areaArray[0]||this.state.areaArray.map((area) => {
                return (
                  <option value={area} key={area}>{area}</option>
                );
              })
            }
          </select>
          <label><input ref="yearSelect" onKeyPress={this.handleKeyPress} className={styles.input} placeholder="如：2016" />年</label>
          <button onClick={this.handleClick} className={styles.button}>确定</button>
        </div>
        <div>
        <Table data={this.state.tData} className={styles.container}>
          <Column dataKey='shopName' name='门店名称' width="200px" order="false" key={`col-shopName`}/>
          <Column dataKey='shopLoc' name='所属地区' width="200px" order="false" key={`col-shopName`}/>
          { 
            //order设置是否开启排序，默认开启
            !this.state.tData[0]||Object.keys(this.state.tData[0]).map(entry => {
              if(/\d/.test(entry)) {
                return <Column dataKey={entry} name={entry} width="100px" key={`col-${entry}`}/>
              }              
            })            
          }
          <Column dataKey='yearTurnover' name='年营业额' width="200px" order="false" key={`col-yearKll`}/>
        </Table>
        </div>
      </div>
    );
  }
});